/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 科泰集团教研团队
 * @version 1.0.0
 * @packageName com.ktjiaoyu.controller
 * @fileName SysController.java
 * @createTime 2024/10/22 12:16
 * @lastModify 2024/10/22 12:16
 */
@Controller
@RequestMapping("/main")
public class SysController extends BaseController{
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SysController.class);
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/changePwd")
    public String toChangePwd(){
        return "sys/changePwd";
    }


    @PostMapping("/changePwd")
    public String doChangePwd(String oldPassword,String password){
        try {
            SysUser loginUser = session(Constants.SESSION_USER);
            if(loginUser.getPassword().equals(oldPassword)) {
                // 通过检查
                SysUser dbSysUser = new SysUser();
                dbSysUser.setId(loginUser.getId());
                dbSysUser.setPassword(password);
                boolean ok = sysUserService.saveOrUpdate(dbSysUser);
                if(ok){
                    // 注销
                    session().invalidate();
                    // 注销并回到登录页
                    return redirect("/login");
                }else{
                    request("error", "修改密码失败！");
                }
            }else{
                request("error", "修改密码失败！");
            }
        } catch (Exception e) {
            LOGGER.error("SysController中的" +
                    "doChangePwd方法执行发生错误。", e);
        }
        return "sys/changePwd";
    }

    @ResponseBody
    @GetMapping("/oldPasswordCheck")
    public Map oldPasswordCheck(@RequestParam String oldPassword){
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if(StringUtils.isEmpty(oldPassword)){
            resultMap.put("pass", 0);
        }else{
            try {
                SysUser loginUser = session(Constants.SESSION_USER);
                if(loginUser.getPassword().equals(oldPassword)) {
                    // 通过检查
                    resultMap.put("pass", 1);
                }else {
                    resultMap.put("pass", 0);
                }
            } catch (Exception e) {
                LOGGER.error("SysController中的" +
                        "oldPasswordCheck方法执行发生错误。", e);
                resultMap.put("error", "出现异常，请联系管理员处理！");
            }
        }
        return resultMap;
    }
}
